package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.domain.User;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

//游记评论业务实现类
@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    //注入游记评论数据接口
    @Autowired
    private TravelCommentRepository travelCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;


    //根据游记评论id查询游记评论信息
    @Override
    public TravelComment get(String id) {
        return travelCommentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(TravelComment travelComment , User user) {
        //用户信息
        //bean工具类,拷贝属性,第一个参数为源,第二个是目标
        BeanUtils.copyProperties(user , travelComment);
        //用户id
        travelComment.setUserId(user.getId());
        //创建时间
        travelComment.setCreateTime(new Date());
        //判断是否是评论的评论
        String refCommentId = travelComment.getRefComment().getId();
        if (StringUtils.hasLength(refCommentId)){
            //是则查出回复的评论设置进去
            travelComment.setRefComment(this.get(refCommentId));
        }
        //防止传了id覆盖了数据
        travelComment.setId(null);
        //保存
        travelCommentRepository.save(travelComment);
    }

  
    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }
    //查询游记下的评论
    @Override
    public Page<TravelComment> list(TravelCommentQuery qo) {
        //创建条件对象
        Query query = new Query();
        //调用数据库工具类查询
        return DBHelper.PagingQuery(mongoTemplate, query, TravelComment.class,qo.getPageable());
    }
    //游记下的评论
    @Override
    public List<TravelComment> queryByTravelId(TravelCommentQuery qo) {

        return travelCommentRepository.findByTravelId(qo.getTravelId());
    }
}
